#!/usr/bin/env bash\

#定义全局常量
proxyUrl=http://192.168.1.113:10808

#1.添加host

#从files文件的hosts中获取对应的hostname  hostname -I 是获取局域网ip  hostname -i 可能会获取到环回网络ip
hostnamectl set-hostname $(grep `hostname -I` /tmp/hosts|awk '{print $2}')

#配置hosts 删除掉所有已配置的host文件
if ! grep -q "223.5.5.5" /etc/resolv.conf; then
    echo "nameserver 223.5.5.5" >> /etc/resolv.conf
fi

if ! grep -q "114.114.114.114" /etc/resolv.conf; then
    echo "nameserver 114.114.114.114" >> /etc/resolv.conf
fi

for line in `cat /tmp/hosts`
do 
    sed -i "/$line/d" /etc/hosts
done

cat /tmp/hosts >> /etc/hosts

#2.配置yum源镜像

#(1)判断yum做了代理没
grep -q "^proxy" /etc/yum.conf
if [ $? -ne 0 ];then
    echo "proxy=${proxyUrl}" >> /etc/yum.conf
fi

#(2)判断yum做了阿里镜像源
if ! grep -q "aliyun" /etc/yum.repos.d/CentOS-Base.repo; then
    cp /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.back
    curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo
    
    if [ $? -ne 0 ]; then
       exit 1
    fi

    yum clean all
    yum makecache
    
    if [ $? -ne 0 ]; then 
       exit 1
    fi
fi
if ! yum list installed |grep -q expect;then
    yum -y install expect -y
fi

#3.添加互信 
#3.1生成密钥
ssh-keygen -f ~/.ssh/id_rsa -P '' -q

for line in `cat /tmp/hosts`
do
    ip=`echo $line|awk '{print $1}'`
    password={{ ansible_ssh_pass }}
    
    expect -c"
    spawn ssh-copy-id -i /root/.ssh/id_rsa.pub $ip
    expect {
        \"(yes/no)?\" { send \"yes\r\"; expect \"*assword:\" {send \"$password\r\"} }
        \"*password:\" { send \"$password\r\" }
    }
    expect eof"
done

#4.时间同步
yum install chrony -y
systemctl start chronyd
systemctl enable chronyd
chronyd sources

#5.关闭防火墙
systemctl stop firewalld
systemctl disable firewalld

#6.关闭swap
swapoff -a
sed -ri 's/.*swap.*/#&/' /etc/fstab

#7.禁用selinux
setenforece 0
sed -i 's/^SELINUX=enforcing$/SELINUX=disabled/' /etc/selinux/config

#8.允许iptables检查桥接流量
sudo modprobe br_netfilter
lsmod | grep br_netfilter

#9.编写k8s.conf文件并加载内核模块
rm -rf /etc/modules-load.d/k8s.conf

cat <<EOF |sudo tee /etc/modules-load.d/k8s.conf
overlay
br_netfilter
EOF

#overlay 允许在不影响底层系统的情况下对文件系统进行更改。
sudo modprobe overlay
#br_netfilter 提供对桥接网络的数据包进行过滤和修改的能力
sudo modprobe br_netfilter

rm -rf /etc/sysctl.d/k8s.conf

# 设置所需的 sysctl 参数，参数在重新启动后保持不变
cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-iptables  = 1
net.bridge.bridge-nf-call-ip6tables = 1
net.ipv4.ip_forward                 = 1
EOF



# 应用 sysctl 参数而不重新启动
sudo sysctl --system
